package com.mazaiting.auth.advice;

import com.mazaiting.common.core.domain.result.Result;
import com.mazaiting.common.core.domain.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 认证异常处理器
 */
@Slf4j
@RestControllerAdvice
public class AuthExceptionAdvice {

    /**
     * 用户不存在
     *
     * @param e 异常
     * @return
     */
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(UsernameNotFoundException.class)
    public Result<?> handleUsernameNotFoundException(UsernameNotFoundException e) {
        log.error("用户名未发现: " + e.getMessage());
        return Result.failed(e.getMessage());
    }

    /**
     * 用户名和密码异常
     *
     * @param e 异常
     * @return
     */
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(InvalidGrantException.class)
    public Result<?> handleInvalidGrantException(InvalidGrantException e) {
        log.error("无效授权: " + e.getMessage());
        return Result.failed(ResultCode.USERNAME_OR_PASSWORD_ERROR.getCode(), e.getMessage());
    }


    /**
     * 账户异常(禁用、锁定、过期)
     *
     * @param e 异常
     */
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({InternalAuthenticationServiceException.class})
    public Result<?> handleInternalAuthenticationServiceException(InternalAuthenticationServiceException e) {
        log.error("账户异常: " + e.getMessage());
        return Result.failed(e.getMessage());
    }

    /**
     * token 无效或已过期
     *
     * @param e 异常
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({InvalidTokenException.class})
    public Result<?> handleInvalidTokenExceptionException(InvalidTokenException e) {
        log.error("token 无效或已过期: " + e.getMessage());
        return Result.failed(e.getMessage());
    }

}
